package com.shujia.scala

object Demo20List {
  def main(args: Array[String]): Unit = {
    //1、List；不可变，有序，不唯一，底层是数组（练习的内存空间）
    val list: List[Int] = List(1, 2, 32, 12, 4, 123, 12, 412, 31, 41, 232, 14)

    //list的普通方法
    println(list.length)
    println(list.sum)
    println(list.min)
    println(list.max)
    println(list(1))
    println(list.head)
    println(list.last)
    println(list.tail) //获取不含第一个后面的所有的元素
    println(list.reverse) //反转
    println(list.take(2)) //取前几

    //list高级方法
    //1、map:对列表中的元素进行处理
    list
      //奇数乘2偶数加1
      .map((i: Int) => if (i % 2 == 1) i * 2 else i + 1)
      .foreach(println)

    //2、filter,当函数返回True保留数据，当函数返回false过滤数据
    val filterList: List[Int] = list
      .filter((i: Int) => i % 2 == 1)

    println(filterList)

    //3、flatMap:一行转换成多行
    val lines: List[String] = List("java,spark,hive", "java,hive,hadoop")

    val words: List[String] = lines
      .flatMap((line: String) => line.split(","))

    println(words)

    //4、sortBy:通过某个字段进行排序
    val sortByList: List[Int] = list
      .sortBy((i: Int) => -i)
    println(sortByList)

    //5、sortWith:定义排序规则
    val sortWithList: List[String] = words
      .sortWith((s1: String, s2: String) => if (s1.compareTo(s2) > 0) false else true)

    println(sortWithList)

    //6、groupBy:指定字段进行分组
    val groupByList: Map[String, List[String]] = words
      .groupBy((word: String) => word)

    println(groupByList)

    val wordCount: Map[String, Int] = groupByList
      //Map集合的map方法，参数一个元组
      .map(kv => {
        val word: String = kv._1
        val count: Int = kv._2.length
        (word, count)
      })

    println(wordCount)

  }
}
